import loadFromStorage from "../../utils/load-from-storage"
import getDefaultDB from "./default-db"

const db = loadFromStorage('database', getDefaultDB)
console.log(db)

function reset() {
    for (let table in db) {
        delete db[table]
    }
    const defaultDB = getDefaultDB()
    for (let table in defaultDB) {
        db[table] = defaultDB[table]
    }
}

function getTable(tableName) {
    let table = db[tableName]
    if (!table || !(table instanceof Array)) {
        table = db[tableName] = []
    }
    return table
}

function queryOne(tableName, prop, value) {
    return getTable(tableName).find(row => row[prop] === value)
}

function fuzzyQuery(tableName, prop, value) {
    if (!value.replaceAll) return getTable(tableName).filter(row => row[prop] === value)
    const r = RegExp(`^${value.replaceAll('', '.*?')}$`)
    return getTable(tableName).filter(row => r.test(row[prop]))
}

function insertOne(tableName, row) {
    getTable(tableName).push(row)
}

function selectAll(tableName) {
    return getTable(tableName)
}

function getConfig(key) {
    return db.__config__[key]
}

function setConfig(key, value) {
    db.__config__[key] = value
}

export {queryOne, fuzzyQuery, insertOne, selectAll, reset, getConfig, setConfig}